from PIL import Image
import io
import os,re

class CompressImage():
    def __init__(self,img_path,byte_size):
        split_dir = os.path.split(img_path)
        self.main_path = split_dir[0]
        file_path = split_dir[1]
        target = r'\.([^\.]+?)$'
        img_type = re.search(target,file_path).group(1)
        if not(img_type=='png' or img_type=='PNG'):
            self.path=os.path.join(self.main_path,re.sub(target,'.png',file_path))
        else:
            self.path=img_path
        self.byte_size = byte_size
        self.img = Image.open(img_path)
        self.size = self.img.size


    def _get_byte_size(self,res):
        imgByteArr = io.BytesIO()
        res.save(imgByteArr, format='PNG')
        imgByteArr = imgByteArr.getvalue()
        return len(imgByteArr)

    def do_it(self):
        print('正在压缩图片...')
        rate = 1
        while rate>0.3:
            new_size = (int(self.size[0]*rate),int(self.size[1]*rate))
            res = self.img.resize(new_size,Image.ANTIALIAS)
            if self._get_byte_size(res)/1024<self.byte_size:
                res.save(self.path,qulity=95)
                res.close()
                self.img.close()
                print('缩放倍率为%f' %rate)
                return self.path
            rate-=0.1
        else:
            print('#####图片缩小到0.4倍依然达不到要求大小。\n')

if __name__=='__main__':
    path = r'C:\Users\Administrator\Desktop\test\公众号\图片\1566278739.jpg'
    C = CompressImage(path,500)
    print(C.do_it())

